using System;
using Microsoft.Research.Kinect.Nui;
using Microsoft.Xna.Framework;


namespace KineBall
{
    public class TrackedSkeleton
    {
        public SkeletonData trackedSkeleton;
        public Vector3 rightPosition3D, leftPosition3D;
    }

    public class KinectManager
    {
        Game game;
        TrackedSkeleton ts;

        Runtime nui;

        float dt;

        public KinectManager(Game game)
        {
            this.game = game;
            ts = new TrackedSkeleton();

            if (game.Services.GetService(typeof(TrackedSkeleton)) == null)
                game.Services.AddService(typeof(TrackedSkeleton), ts);
        }

        public void Initialize()
        {
            SetupKinect();
        }

        public void Update(GameTime gameTime)
        {
            dt += (float)gameTime.ElapsedGameTime.TotalSeconds;

            if (ts.trackedSkeleton != null)
            {
                SkeletonData skeleton = ts.trackedSkeleton;

                var handRight = skeleton.Joints[JointID.HandRight];
                var handLeft = skeleton.Joints[JointID.HandLeft];

                ts.rightPosition3D = new Vector3(handRight.Position.X, handRight.Position.Y, handRight.Position.Z);
                ts.leftPosition3D = new Vector3(handLeft.Position.X, handLeft.Position.Y, handLeft.Position.Z);
            }
        }

        private void SetupKinect()
        {
            nui = Runtime.Kinects[0];
            nui.Initialize(RuntimeOptions.UseSkeletalTracking);
            nui.SkeletonFrameReady += new EventHandler<SkeletonFrameReadyEventArgs>(nuiSkeletonFrameReady);

            nui.SkeletonEngine.TransformSmooth = true;
            TransformSmoothParameters parameters = new TransformSmoothParameters();
            parameters.Smoothing = 0.7f;
            parameters.Correction = 0.3f;
            parameters.Prediction = 0.8f;
            parameters.JitterRadius = 1.0f;
            parameters.MaxDeviationRadius = 0.5f;
            nui.SkeletonEngine.SmoothParameters = parameters;
        }

        void nuiSkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs e)
        {
            SkeletonFrame allSkeletons = e.SkeletonFrame;

            foreach (SkeletonData s in allSkeletons.Skeletons)
            {
                if (s.TrackingState == SkeletonTrackingState.Tracked)
                {
                    ts.trackedSkeleton = s;
                    return;
                }
            }
            ts.trackedSkeleton = null;
        }
    }
}
